#include ".\list.h"
void List::destroy(){	
	for(int i=0; i<this->m_filled_in; i++) delete list[i];
	if(capacity( )){
		if(capacity( )==1) delete list;
		else delete[] list;
	}
	this->m_size = 0;
	this->m_filled_in = 0;
	list = NULL;
}
void List::allocate( size_type initialSize ){
	if(initialSize > max_size()) throw "Some Exception";
	if(initialSize){
		if(initialSize == 1) list = new vehicule*;
		else list = new vehicule*[initialSize];
	}
	this->m_size = initialSize;
	this->m_filled_in = 0;
}

void List::insert(const vehicule& v){
      if(m_filled_in < capacity( )){ 
			list[m_filled_in] = v.clone( );
			m_filled_in++;
            return;
            }
	  size_type NewSize = (capacity( )+ m_inc_size < max_size())?capacity( )+ m_inc_size:max_size();

	  resize(NewSize);
      insert(v);
}; // insert another vehicle

void List::resize(int n){
	//First do some verifications
    if((n > max_size()) || (n < 0))
		throw "some exception that says that the argument is bad";
	
	int old_m_filled_in = m_filled_in;
	vehicule** NewArray = new vehicule*[n];
    int i=0;
    for(i; (i < m_filled_in && i < n); i++)
		NewArray[i] =  list[i]->clone( ); 
	
	destroy();
	list = NewArray;
	m_size = n;
	m_filled_in = old_m_filled_in;
	if(size( ) > capacity( )) m_filled_in = capacity( );
}
bool List::gt(char const* const str1, char const* const str2){
	int ctr=0;
	int str1Size1=0; while(str1[str1Size1])str1Size1++;
	int str1Size2=0; while(str2[str1Size2])str1Size2++;

	while((ctr < str1Size1) && (ctr < str1Size2)){
		if(str1[ctr] < str2[ctr])
			return false;
		if(str1[ctr] > str2[ctr])
			return true;
		ctr++;
	}
	if(str1Size1 <= str1Size2) return false;
	return true;
}
void List::sort_inventory(){
	bool finished=false;
	int num=0;
	vehicule** newArray = new vehicule*[this->capacity( )];
	while(!finished){
		int curr=0;
		while((!list[curr])&&(curr < size( )))curr++;
		if(curr >= size( )) finished = true;
		else
			for(int i=curr; i<size(); i++){
			if(list[i])
				if(gt(list[curr]->key_inventory( ), list[i]->key_inventory( ))) curr=i;
		}
		newArray[num++]=list[curr]; list[curr]=NULL;
	}
	delete[]list; 
	list = newArray;
}

